<script setup>
import request from "@/utils/request";
import rcVillages from '@/assets/rcVillages.json';
import rcStreets from '@/assets/rcStreets.json';
import { ref, onMounted } from 'vue';

const form = ref({});
const address = ref({
    area: '荣成市',
    selectedStreet: {},
    selectedVillage: {},
    detail: '',
    nextVillages: []
});
address.value.rcVillages = rcVillages;
address.value.rcStreets = rcStreets;

const loadAddress = (addressStr) => {
    const addStr = addressStr.split('-');
    if (addStr[1] === ' ') {
        address.value.selectedStreet = {};
    } else {
        rcStreets.forEach(ele => {
            if (ele.name === addStr[1]) {
                address.value.selectedStreet = ele;
                onStreetChange();
            }
        });
    }

    if (addStr[2] === ' ') {
        address.value.selectedVillage = {};
    } else {
        rcVillages.forEach(ele => {
            if (ele.name === addStr[2]) {
                address.value.selectedVillage = ele;
            }
        });
    }

    if (addStr[3] === ' ') {
        address.value.detail = '';
    } else {
        address.value.detail = addStr[3];
    }
};

const handleAvatarSuccess = (res) => {
    form.value.avatar = res.data;
    // 假设 $message 是通过 app.config.globalProperties.$message 挂载的全局方法
    app.config.globalProperties.$message.success("上传成功");
    // this.update();
};

const update = () => {
    let newAddress = address.value.area;
    if (Object.keys(address.value.selectedStreet).length === 0) {
        console.log('街道未选择，初始化为空串');
        newAddress += '- ';
    } else {
        console.log('街道已选择，不为空');
        newAddress += '-' + address.value.selectedStreet.name;
    }

    if (Object.keys(address.value.selectedVillage).length === 0) {
        console.log('村委会未选择，初始化为空串');
        newAddress += '- ';
    } else {
        console.log('村委会已选择');
        newAddress += '-' + address.value.selectedVillage.name;
    }

    if (address.value.detail === '') {
        console.log('详细地址未填写,初始化为空串');
        newAddress += '- ';
    } else {
        console.log('详细地址已填写');
        newAddress += '-' + address.value.detail;
    }

    console.log('新地址', newAddress);
    form.value.address = newAddress;
    request.put("/user", form.value).then(res => {
        if (res.code === '0') {
            app.config.globalProperties.$message({
                type: "success",
                message: "更新成功"
            });
            sessionStorage.setItem("user", JSON.stringify(form.value));
            // 触发Layout更新用户信息
            // 这里假设在setup语法糖中，通过defineEmits定义了emit函数
            const emit = defineEmits(['userInfo']);
            emit('userInfo');
        } else {
            app.config.globalProperties.$message({
                type: "error",
                message: res.msg
            });
        }
    });
};

const onStreetChange = () => {
    console.log('当前选择的街道/镇 是', address.value.selectedStreet);
    address.value.nextVillages = [];
    rcVillages.forEach((element) => {
        if (element.streetCode === address.value.selectedStreet.code) {
            address.value.nextVillages.push(element);
        }
    });
    console.log('已加载此街道所有的村', address.value.nextVillages);
};

onMounted(() => {
    const str = sessionStorage.getItem("user") || "{}";
    form.value = JSON.parse(str);
    loadAddress(form.value.address);
});
</script>

<template>
  <div>
    <el-card style="width: 40%; margin: 10px">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item style="text-align: center" label-width="0">
          <el-upload class="avatar-uploader" action="http://localhost:9090/files/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="男" value="男" />
            <el-radio label="女" value="女" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form :model="address" label-width="100px">
        <el-form-item label="地址">
          <el-select v-model="address.area" placeholder="荣成市" disabled>
          </el-select>
          <el-select v-model="address.selectedStreet" placeholder="请选择乡镇/街道" @change="onStreetChange" value-key="code"
            :clearable="true">
            <el-option v-for="(item) in rcStreets" :key="item" :value="item" :label="item.name" />
          </el-select>
          <el-select v-model="address.selectedVillage" placeholder="村委会(非必选)" value-key="code" :clearable="true">
            <el-option v-for="(item) in address.nextVillages" :key="item" :value="item" :label="item.name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="address.detail" type="textarea" :clearable="true" />
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="update">保存</el-button>
      </div>
    </el-card>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
